Analog Digital Converter

Contenido

Usando el convertidor Analogico-Digital del microcontrolador Atmega168pa.

Ejemplo usando un sensor LDR (Light Dependent Resistor)

Circuito

Analog Digital Converter SimulIDE

#include <avr/io.h>
#include <util/delay.h>

int main(void) {

  uint8_t ledValue;
  uint16_t adcValue;

  ADMUX |= (1 << REFS0);                  /* reference voltage on AVCC */
  ADCSRA |= (1 << ADPS2);                   /* ADC clock prescaler /16 */
  ADCSRA |= (1 << ADEN);

  DDRB = 0xff;

  while (1) {

    ADCSRA |= (1 << ADSC);                     /* start ADC conversion */
    loop_until_bit_is_clear(ADCSRA, ADSC);          /* wait until done */
    adcValue = ADC;                                     /* read ADC in */
                        
    /* Have 10 bits, want 3 (eight LEDs after all) */
    ledValue = (adcValue >> 7);
                                   
    /* Light up all LEDs up to ledValue */
    PORTB = 0;
    for (uint8_t i = 0; i <= ledValue; i++) {
      PORTB |= (1 << i);
    }
    _delay_ms(50);
  }                                                  /* End event loop */
  return 0;                            /* This line is never reached */
}
Tags

AVR | ADC | LDR